package controllers

import (
	"encoding/json"
	"exp1/cache"
	"exp1/models"
	"exp1/pkg"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"time"
)

type Exp1Controller struct {
	beego.Controller
}

func (c *Exp1Controller) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "用户或密码为空",
		}
		c.ServeJSON()
		return
	}
	loginErrorkey := "loginError" + username
	ErrorCount, _ := cache.Rdb.Get(cache.Ctx, loginErrorkey).Int()
	if ErrorCount >= 3 {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "密码错误三次，禁止登录",
		}
		c.ServeJSON()
		return
	}
	var err error
	var user models.User
	//err = models.DB.Where("username=?", username).First(&user).Error
	err = user.LoginUser(username, &user)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "用户不存在",
		}
		c.ServeJSON()
		return
	}
	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, loginErrorkey) //密码错误一次，错误值加一
		if ErrorCount == 2 {
			cache.Rdb.Set(cache.Ctx, loginErrorkey, 3, time.Hour*1)
			c.Data["json"] = map[string]interface{}{
				"code": 0,
				"msg":  "密码错误三次",
			}
			c.ServeJSON()
			return
		}
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "密码错误",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	}
	c.ServeJSON()
	return

}

// 角色-权限 添加
func (c *Exp1Controller) RoleNodeAdd() {
	rid, _ := c.GetInt("rid", 0)
	nid, _ := c.GetInt("nid", 0)
	if rid == 0 || nid == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "用户或密码为空",
		}
		c.ServeJSON()
		return
	}
	data := models.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	var err error
	//err = models.DB.Create(&data).Error
	_, err = data.RoleNodeAdd(&data)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "添加成功",
			"data": data,
		}
		c.ServeJSON()
		return
	}
}

// 用户-角色 查询
func (c *Exp1Controller) UserRole() {
	uid, _ := c.GetInt("uid", 0)
	if uid == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "用户id为空",
		}
		c.ServeJSON()
		return
	}
	var Role models.Role
	//err := models.DB.Table("roles").
	//	Joins("left join user_role on user_roles.rid =roles.rid").
	//	Where("user_roles.uid-?", uid).
	//	Find(&Role).Error
	err := models.DB.Table("roles").
		Joins("left join user_roles on user_roles.rid =roles.id").
		Where("user_roles.uid=?", uid).
		Find(&Role).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "查询失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "查询成功",
			"data": Role,
		}
		c.ServeJSON()
		return
	}
}

// 角色-权限 查询
func (c *Exp1Controller) RoleNodeList() {
	rid, _ := c.GetInt("rid", 0)
	if rid == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "角色id为空",
		}
		c.ServeJSON()
		return
	}
	var Node []models.Node
	err := models.DB.Table("nodes").Joins("left join role_nodes on role_nodes.nid=nodes.id").Where("role_nodes.rid=?", rid).First(&Node).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "查询失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "查询成功",
			"data": Node,
		}
		c.ServeJSON()
		return
	}

}

// 物流公司 添加
func (c *Exp1Controller) CompAdd() {
	name := c.GetString("name")
	if name == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "物流公司名称为空",
		}
		c.ServeJSON()
		return
	}
	comp := models.Comp{
		CompName: name,
	}
	_, err := comp.Compadd(&comp)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "添加成功",
			"data": comp,
		}
		c.ServeJSON()
		return
	}

}

// 快递订单 添加
func (c *Exp1Controller) OrdersAdd() {
	ordersNum := c.GetString("ordersNum")
	cid, _ := c.GetInt("cid", 0)
	eid, _ := c.GetInt("eid", 0)
	if ordersNum == "" || cid == 0 || eid == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "订单号，物流公司id或物流类型id为空",
		}
		c.ServeJSON()
		return
	}
	orders := models.Orders{
		OrdersNum: ordersNum,
		Cid:       cid,
		Eid:       eid,
	}
	_, err := orders.Ordersadd(&orders)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "添加成功",
			"data": orders,
		}
		c.ServeJSON()
		return
	}
}

// 快递单列表
func (c *Exp1Controller) OrdersList() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 2)
	offset := (page - 1) * size

	var list []models.OrdersListData
	listKey := "list_page_" + strconv.Itoa(page)
	cacheList, _ := cache.Rdb.Get(cache.Ctx, listKey).Result()
	if cacheList == "" {
		models.DB.Table("orders").
			Joins("left join comps on comps.id=orders.cid").
			Joins("left join exps on exps.id=orders.eid").
			Offset(offset).Limit(size).
			Select("orders.id as id,orders.orders_num as orders_num,comps.id as cid,comps.comp_name as comp_name,exps.id as eid,exps.exp_name as exp_name").
			Debug().Find(&list)
		cacheData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, listKey, cacheData, time.Hour*1)
	} else {
		json.Unmarshal([]byte(cacheList), &list)
	}
	var count int64
	models.DB.Table("orders").Count(&count)
	c.Data["json"] = map[string]interface{}{
		"code":  200,
		"msg":   "查询成功",
		"data":  list,
		"count": count,
	}
	c.ServeJSON()
	return

}

// 快递详情
func (c *Exp1Controller) Details() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id", 0)
	if id == 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "字段为空",
		}
		c.ServeJSON()
		return
	}
	var ordersData models.Orders
	detailKey := "detail_" + strconv.Itoa(id)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, detailKey).Result()
	if cacheData == "" {
		models.DB.Find(&ordersData)
		cahceJson, _ := json.Marshal(ordersData)
		cache.Rdb.Set(cache.Ctx, detailKey, cahceJson, time.Hour*1)
	} else {
		json.Unmarshal([]byte(cacheData), &ordersData)
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "查询成功",
		"data": ordersData,
	}
	c.ServeJSON()
	return
}
